@echo off

set JAVA_HOME=C:\Program Files\Java\JDK1.7.0_13
set M2_HOME=%~dp0maven
set MAVEN_OPTS=-Xmx512M -Xms64M -DUseSunHttpHandler=true

:loop_maven
  for %%i in ("mvn.bat") do set MAVEN_BIN_DIR=%%~dp$PATH:i
  if not "%MAVEN_BIN_DIR%" == "" goto :else_mavenbat
    set path=%M2_HOME%\bin;%path%
    goto :endloop_maven
  :else_mavenbat
    if "%MAVEN_BIN_DIR:~-1%" == "\" set MAVEN_BIN_DIR=%MAVEN_BIN_DIR:~0,-1%
    if "%MAVEN_BIN_DIR%" == "%M2_HOME%\bin" goto :endloop_maven
    call :removepath "%MAVEN_BIN_DIR%"
  :endif_mavenbat
  goto :loop_maven
:endloop_maven
set MAVEN_BIN_DIR=

for %%i in ("java.exe") do set JAVA_EXE=%%~$PATH:i
if not "%JAVA_EXE%" == "" goto :endif_javaexe
  if not "%JAVA_HOME%" == "" goto :endif_javaexe_javahome
	echo ERROR: java.exe not in path and no java_home specified
	exit /b 1
  :endif_javaexe_javahome
  set path=%JAVA_HOME%\bin;%path%
:endif_javaexe
set JAVA_EXE=

for %%i in ("javac.exe") do set JAVAC_EXE=%%~$PATH:i
if not "%JAVAC_EXE%" == "" goto :endif_javacexe
  if not "%JAVA_HOME%" == "" goto :endif_javacexe_javahome
	echo ERROR: javac.exe not in path and no java_home specified
	exit /b 1
  :endif_javacexe_javahome
  set path=%JAVA_HOME%\bin;%path%
:endif_javacexe

if not "%JAVA_HOME%" == "" goto :endif_javahome
  for %%i in ("%JAVAC_EXE%") do set JAVA_BIN_DIR=%%~dpi
  set JAVA_BIN_DIR=%JAVA_BIN_DIR:~0,-1%
  for %%i in ("%JAVA_BIN_DIR%") do set JAVA_HOME=%%~dpi
  set JAVA_HOME=%JAVA_HOME:~0,-1%
:endif_javahome
set JAVAC_EXE=
set JAVA_BIN_DIR=

echo M2_HOME = %M2_HOME%
echo JAVA_HOME = %JAVA_HOME%
echo path = %path%

goto :end

:removepath
  set args=%path:\=\B%
  set args=%args: =\S%
  set args=%args:;= %
  call :removepath_impl %1 %args%
  set args=
  goto :end
:end_removepath

:removepath_impl
  set item=%1
  for %%i in (%item%) do set item=%%~fsi
  shift
  set newpath=
  :loop_removepath
    if "%1" == "" goto :endloop_removepath
    set arg=%1
    set arg=%arg:\S= %
    set arg=%arg:\B=\%
    for %%i in ("%arg%") do set fsarg=%%~fsi
    if "%fsarg%" == "%item%" goto :endif_removepath
      if not "%newpath%" == "" set newpath=%newpath%;
      set newpath=%newpath%%arg%
    :endif_removepath
    shift
    goto :loop_removepath
  :endloop_removepath
  set path=%newpath%
  set fsarg=
  set item=
  set arg=
  set newpath=
  goto :end
:end_removepath_impl

:end